package com.example.demo.utils;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class GetMoney {
    private double money = 100000;
    private final Lock lk = new ReentrantLock();

    public void drawMoney(double money) {
        String name = Thread.currentThread().getName();
        synchronized (this) {
            if (money <= this.money) {
                this.money -= money;
                System.out.println(name + "来取钱：" + money + ",余额：" + this.money);
            } else {
                System.out.println(name + "来取钱,余额不足");
            }
        }
    }

    public synchronized void drawMoney2(double money) {
        String name = Thread.currentThread().getName();
        if (money <= this.money) {
            this.money -= money;
            System.out.println(name + "来取钱：" + money + ",余额：" + this.money);
        } else {
            System.out.println(name + "来取钱,余额不足");
        }
    }

    public void drawMoney3(double money) {
        String name = Thread.currentThread().getName();
        lk.lock();//加锁
        try {
            if (money <= this.money) {
                this.money -= money;
                System.out.println(name + "来取钱：" + money + ",余额：" + this.money);
            } else {
                System.out.println(name + "来取钱,余额不足");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lk.unlock();//解锁
        }
    }
}
